
#include "stdafx.h"
#include "Curlplus.h"
#include <iostream>

auto_ptr<Curlplus> Curlplus::_instance;
string Curlplus::s_Buffer;
static char errorBuffer[CURL_ERROR_SIZE]; 

Curlplus& Curlplus::get_instance()
{
    if(_instance.get() == NULL)
    {
        _instance.reset(new Curlplus());
    } 

    return *_instance.get();
}

int Curlplus::writer(char *data, size_t size, size_t nmemb, string *writerData)
{
    if (writerData == NULL)
        return 0;
    int len = size*nmemb;
    writerData->append(data, len);

    return len;
}

Curlplus::Curlplus(void)
{ 
	CURLcode code = curl_global_init(CURL_GLOBAL_ALL);
    if(code != CURLE_OK)
    {
        cout << "curl_init failed, error code is: " << code;
    }
}

Curlplus::~Curlplus(void)
{
    curl_global_cleanup();
} 

string Curlplus::post(const string& url, const string& content) const
{
    s_Buffer="";
    CURL *curl = curl_easy_init();
    if(curl == NULL)
    {
        cout << "curl_easy_init failed ";
    }  

    _setCurlopt(curl,url);
    curl_easy_setopt(curl, CURLOPT_POST, 1 );
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, content.c_str());   

    CURLcode code = curl_easy_perform(curl);
    if(code != CURLE_OK)
    {
        cout << "curl_easy_perform failed: "<< code;
    }
    curl_easy_cleanup(curl);

    return s_Buffer;
} 

string Curlplus::get(const string& url) const
{
    s_Buffer="";
    CURL *curl = curl_easy_init();
    if(curl == NULL)
    {
        cout << "curl_easy_init failed ";
    }  

    _setCurlopt(curl,url);
    CURLcode code = curl_easy_perform(curl); 

    if(code != CURLE_OK)
    {
        cout << "curl_easy_perform failed: "<< code;
    }
    curl_easy_cleanup(curl);
    return s_Buffer;
}

void Curlplus::_setCurlopt(CURL *curl,const string& url) const 
{
    curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
    curl_easy_setopt(curl, CURLOPT_HEADER, 0);
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, s_Defaulttimeout);
    //curl_easy_setopt(curl, CURLOPT_VERBOSE, true);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, Curlplus::writer);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s_Buffer);

}